/**
 * 2009-10-27 下午04:37:39 
 * esignature
 * com.smc.dao.impl
 * DocumentDaoService
 */
package com.smc.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.smc.action.document.NumDocument;
import com.smc.dao.DocumentDao;
import com.smc.domain.model.Document;
import com.smc.domain.model.Hospital;
import com.smc.domain.model.User;

/**
 * @author chenheng
 * @version 0.0.1
 * 持久层文档接口实现
 */
public class DocumentDaoImpl extends HibernateDaoSupport implements DocumentDao {
	
	@SuppressWarnings("unchecked")
	public List<Document> fetch_US_DO_FE_document(boolean signed,String uuid,int pageIndex,int pageSize) {
		User user = (User) getHibernateTemplate().load(User.class, uuid); 
		String hql = "FROM Document d WHERE d.user = ? AND d.signed = ?";
		Session session = getSession();
		Query query = session.createQuery(hql);
		query.setFirstResult((pageIndex-1)*pageSize);
		query.setMaxResults(pageSize);
		query.setParameter(0, user);
		query.setParameter(1, signed);
		return query.list();
	}
	public int count_US_DO_FE_document(boolean signed,String uuid) {
		Long count ;
		User user = (User) getHibernateTemplate().load(User.class, uuid);
		String hql = "SELECT COUNT(*) FROM Document d WHERE d.user = ? AND d.signed = ?" ;
		Object[] params = new Object[]{user,signed};
		count = (Long)getHibernateTemplate().find(hql,params).iterator().next();
		return count.intValue();
	}
	public void save_OP_DO_SA_document(Document document) {
		Hospital hospital = (Hospital) getHibernateTemplate().load(Hospital.class, document.getHospitalUuid());
		User user = (User) getHibernateTemplate().load(User.class, document.getUserUuid());
		document.setHospital(hospital);
		document.setUser(user);
		getHibernateTemplate().saveOrUpdate(document);
	}

	@SuppressWarnings("unchecked")
	public Document fetch_US_DO_FE_document(String uuid) {
		String hql = "FROM Document d WHERE d.uuid = ? ";
		List<Document> dl = getHibernateTemplate().find(hql, uuid);
		Document d = null ;
		if ( dl.size() > 0 ) {
			d = dl.iterator().next();
		}
		return d;
	}

	public void save_US_DO_SA_document(Document document) {
		Session session = getSession();
		Document d = (Document) session.get(Document.class, document.getUuid());
		d.setPatient(document.getPatient());
		d.setIntroduction(document.getIntroduction());
		d.setSigned(document.isSigned());
		d.setSignTime(document.getSignTime());
		Transaction tx = session.beginTransaction();
		session.saveOrUpdate(d);
		session.flush();
		tx.commit();
	}
	@SuppressWarnings("unchecked")
	public List<Document> fetch_HO_DO_FE_document(String uuid, boolean signed, int pageIndex, int pageSize) {
		Session session = getSession();
		User user =(User) session.get(User.class, uuid);
		String hql = "FROM Document a JOIN FETCH a.user WHERE a.hospital = ? AND a.signed = ?" ;
		Query query = session.createQuery(hql);
		query.setParameter(0,user.getHospital());
		query.setParameter(1, signed);
		query.setFirstResult((pageIndex-1)*pageSize);
		query.setMaxResults(pageSize);
		List<Document> ld = query.list();
		return ld ;
	}
	@SuppressWarnings("unchecked")
	public List<Document> fetch_HO_DO_FE_document(String uuid, String[] parameters, int pageIndex, int pageSize) {
//		Session session = getSession() ;
//		User user = (User) session.load(User.class, uuid);
//		String likeStr = "'%" + parameters[1] +"%'";
//		String hql = "FROM Document a WHERE a.hospital = ? AND a." + parameters[0] + " LIKE " + likeStr ;
//		Query query = session.createQuery(hql);
//		query.setParameter(0, user.getHospital());
//		query.setFirstResult((pageIndex-1)*pageSize);
//		query.setMaxResults(pageSize);
//		List<Document> ld = query.list();
//		return ld;
		Session session = getSession();
		User user = (User) session.get(User.class, uuid);
		StringBuffer sb = new StringBuffer();
		sb.append("FROM Document a JOIN FETCH a.user WHERE a.hospital = ? AND 1 = 1 ");
		String searchKey = null;
		String searchValue = null;
		List<Document> l = null ; 
		Query query = null ;
		if (parameters != null && parameters.length == 2 ) {
			searchKey = parameters[0];
			searchValue = parameters[1];
		}
		if ( ! searchValue.trim().equals("") ) {
			if (searchKey.equals("0")) {
				sb.append("AND a.fileName LIKE ?");
			} else if (searchKey.equals("1")) {
				sb.append("AND a.user.username LIKE ?");
			} else if (searchKey.equals("2")) {
				sb.append("AND a.patient LIKE ?");
			} else {
					
			}
			String value = '%' + searchValue + '%';
			query = session.createQuery(sb.toString());
			query.setParameter(0, user.getHospital());
			query.setParameter(1, value);
		} else {
			query = session.createQuery(sb.toString());
			query.setParameter(0, user.getHospital());
		}
		query.setFirstResult((pageIndex-1)*pageSize);
		query.setMaxResults(pageSize);
		List<Document> ld = query.list();
		return ld ;
	}
	@SuppressWarnings("unchecked")
	public List fetch_HO_DO_FE_documentNum(String uuid, String orderItem, int pageIndex, int pageSize) {
		Session session = getSession();
		User user = (User) session.load(User.class, uuid);
		String hql1 = "SELECT new com.smc.action.document.NumDocument(a.user.uuid,a.user.username,count(a)) FROM Document a " +
				"WHERE a.hospital = ? GROUP BY a.user.uuid ORDER BY a." + orderItem;
		Query query = session.createQuery(hql1);
		query.setParameter(0, user.getHospital());
		query.setFirstResult((pageIndex-1)*pageSize);
		query.setMaxResults(pageSize);
		List<NumDocument> ld = query.list();
		List<NumDocument> lnd = new ArrayList<NumDocument>();
		String hql2 = "SELECT COUNT(b) FROM Document b WHERE b.signed = ? AND b.user.uuid = ? ";
		for ( NumDocument nd : ld ) {
			query = session.createQuery(hql2);
			query.setParameter(0,true);
			query.setParameter(1, nd.getUserUuid());
			List l1 = query.list() ;
			if ( l1.size() > 0 ) {
				nd.setDocSignedNumber(l1.iterator().next());
			}
			query.setParameter(0, false);
			List l2 = query.list();
			if ( l2.size() > 0 ) {
				nd.setDocUnSignedNumber(l2.iterator().next());
			}
			lnd.add(nd);
		}
		return lnd;
	}
	public int count_HO_DO_FE_documentNum(String uuid) {
		Session session = getSession();
		User user = (User) session.get(User.class, uuid);
		String hql = "SELECT COUNT(a) FROM Document a WHERE a.hospital = ? GROUP BY a.user.uuid ";
		Query query = session.createQuery(hql);
		query.setParameter(0, user.getHospital());
		List l = query.list() ;
		int i = 0 ;
		if (l.size() > 0 ) {
			Long count = (Long) l.iterator().next();
			i = count.intValue();
		}
		return i;
	}
	@SuppressWarnings("unchecked")
	public List<NumDocument> fetch_HO_DO_FE_documentRankNum(String uuid,String orderItem, int pageIndex, int pageSize) {
		Session session = getSession();
		User user = (User) session.get(User.class, uuid);
		String hql1 = "SELECT new com.smc.action.document.NumDocument(a.user.uuid,a.user.username,0,0,COUNT(a)) FROM Document a " +
				"WHERE a.hospital = ? AND a.signed = ? GROUP BY a.user.uuid ORDER BY COUNT(a) ";
		Query query = session.createQuery(hql1);
		query.setParameter(0, user.getHospital());
		query.setParameter(1, false);
		query.setFirstResult((pageIndex-1)*pageSize);
		query.setMaxResults(pageSize);
		List<NumDocument> ld = query.list();
		List<NumDocument> lnd = new ArrayList<NumDocument>();
		String hql2 = "SELECT COUNT(b) FROM Document b WHERE b.signed = ? AND b.user.uuid = ? ";
		String hql3 = "SELECT COUNT(c) FROM Document c WHERE c.user.uuid = ?";
		for ( NumDocument nd : ld ) {
			query = session.createQuery(hql2);
			query.setParameter(0,true);
			query.setParameter(1, nd.getUserUuid());
			List l1 = query.list() ;
			if ( l1.size() > 0 ) {
				nd.setDocSignedNumber(l1.iterator().next());
			}
			query = session.createQuery(hql3);
			query.setParameter(0, nd.getUserUuid());
			List l2 = query.list() ;
			if ( l2.size() > 0 ) {
				nd.setDocNumber(l2.iterator().next());
			}
			lnd.add(nd);
		}
		return lnd;
	}
	@SuppressWarnings("unchecked")
	public List<NumDocument> fetch_HO_DO_FE_documentPatientNum(String uuid, String orderItme, int pageIndex, int pageSize) {
		Session session = getSession();
		User user = (User) session.load(User.class,uuid);
		String hql = "SELECT new com.smc.action.document.NumDocument('','',a.patient,a.medicalRecord,COUNT(a),0,0) FROM Document a " +
				"WHERE a.hospital = ? GROUP BY a.medicalRecord ORDER BY COUNT(a) ";
		Query query = session.createQuery(hql);
		query.setParameter(0, user.getHospital());
		query.setFirstResult((pageIndex-1)*pageSize);
		query.setMaxResults(pageSize);
		List<NumDocument> ld = query.list();
		List<NumDocument> lnd = new ArrayList<NumDocument>();
		String hql2 = "SELECT COUNT(b) FROM Document b WHERE b.medicalRecord = ? AND b.signed = ?";
		for ( NumDocument nd : ld ) {
			query = session.createQuery(hql2);
			query.setParameter(0, nd.getMedicalRecord());
			query.setParameter(1, true);
			List l1 = query.list() ;
			if ( l1.size() > 0 ) {
				nd.setDocSignedNumber(l1.iterator().next());
			}
			query.setParameter(1, false);
			List l2 = query.list() ;
			if ( l2.size() > 0 ) {
				nd.setDocUnSignedNumber(l2.iterator().next());
			}
			lnd.add(nd);
		}
		return lnd;
	}
	@SuppressWarnings("unchecked")
	public int count_HO_DO_FE_documentNum(String uuid, boolean signed) {
		Session session = getSession();
		User user = (User) session.get(User.class, uuid);
		String hql = "SELECT COUNT(a) FROM Document a WHERE a.hospital = ? AND a.signed = ?";
		Query query = session.createQuery(hql);
		query.setParameter(0, user.getHospital());
		query.setParameter(1, signed);
		List l = query.list() ;
		int count = 0 ;
		if ( l.size() > 0 ) {
			count = ((Long)l.iterator().next()).intValue();
		}
		return count ;
	}
	public int count_HO_DO_FE_document(String uuid, String[] parameters) {
		Session session = getSession();
		User user = (User) session.get(User.class, uuid);
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT COUNT(a) FROM Document a WHERE a.hospital = ? AND 1 = 1 ");
		String searchKey = null;
		String searchValue = null;
		int count = 0 ;
		if (parameters != null && parameters.length == 2 ) {
			searchKey = parameters[0];
			searchValue = parameters[1];
		}
		if ( ! searchValue.trim().equals("") ) {
			if (searchKey.equals("0")) {
				sb.append("AND a.fileName LIKE ?");
			} else if (searchKey.equals("1")) {
				sb.append("AND a.user.username LIKE ?");
			} else if (searchKey.equals("2")) {
				sb.append("AND a.patient LIKE ?");
			} else {
					
			}
			String value = '%' + searchValue + '%';
			Query query = session.createQuery(sb.toString());
			query.setParameter(0, user.getHospital());
			query.setParameter(1, value);
			List l = query.list() ;
			if ( l.size() > 0 ) {
				count = ((Long) l.iterator().next()).intValue() ;
			}
		} else {
			Query query = session.createQuery(sb.toString());
			query.setParameter(0, user.getHospital());
			List l = query.list() ;
			if ( l.size() > 0 ) {
				count = ((Long) l.iterator().next()).intValue() ;
			}
		}
		return count ;
	}
}
